<template>
  <view class="timer-container">
    <view :class="{ 'warning': isWarning, 'danger': isDanger }" class="timer-display">
      <uni-icons :color="iconColor" size="20" type="clock"></uni-icons>
      <text class="timer-text">{{ formattedTime }}</text>
    </view>
  </view>
</template>

<script>
import CommonUtils from '@/utils/common.js';

export default {
  name: 'Timer',
  props: {
    autoStart: {
      type: Boolean,
      default: true
    },
    warningThreshold: {
      type: Number,
      default: 30
    },
    dangerThreshold: {
      type: Number,
      default: 60
    },
    initialTime: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      time: 0,
      timer: null,
      isRunning: false
    };
  },
  computed: {
    formattedTime() {
      return CommonUtils.formatTime(this.time);
    },
    isWarning() {
      return this.time >= this.warningThreshold && this.time < this.dangerThreshold;
    },
    isDanger() {
      return this.time >= this.dangerThreshold;
    },
    iconColor() {
      if (this.isDanger) return '#ff4757';
      if (this.isWarning) return '#ffa502';
      return '#007AFF';
    }
  },
  mounted() {
    this.time = this.initialTime;
    if (this.autoStart) {
      this.start();
    }
  },
  beforeDestroy() {
    this.stop();
  },
  methods: {
    start() {
      if (this.isRunning) return;

      this.isRunning = true;
      this.timer = setInterval(() => {
        this.time++;
        this.$emit('tick', this.time);
      }, 1000);

      this.$emit('start', this.time);
    },

    stop() {
      if (!this.isRunning) return;

      this.isRunning = false;
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }

      this.$emit('stop', this.time);
    },

    reset() {
      this.stop();
      this.time = this.initialTime;
      this.$emit('reset', this.time);
    },

    getTime() {
      return this.time;
    }
  }
};
</script>

<style lang="scss" scoped>
.timer-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.timer-display {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  background-color: #f8f9fa;
  border: 2rpx solid #007AFF;
  transition: all 0.3s ease;

  &.warning {
    border-color: #ffa502;
    background-color: #fff3cd;
  }

  &.danger {
    border-color: #ff4757;
    background-color: #f8d7da;
    animation: pulse 1s infinite;
  }

  .timer-text {
    font-size: 28rpx;
    font-weight: bold;
    margin-left: 10rpx;
    color: #333;
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}
</style>